package com.example.spingsercurity2.util;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.jsonwebtoken.Claims;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 *从token中获取用户权限信息
 **/
public class JwtUserDetail implements UserDetails {

	private String username;
	private Collection<SimpleGrantedAuthority> authorities;

	public JwtUserDetail( Claims claims) {
		this.username = claims.getSubject();

		//从token中获取权限信息
		List<String> roleAuthorizes = claims.get("roleAuthorizes", List.class);

		//权限和角色都在roleAuthorizes中,和shiro不同,shiro是权限和角色分开的
		authorities = new ArrayList<>(roleAuthorizes.size());
		roleAuthorizes.forEach((roleAuthorize) -> {
			authorities.add(new SimpleGrantedAuthority(roleAuthorize));
		});
	}

	@Override
	public Collection<SimpleGrantedAuthority> getAuthorities() {
		return authorities;
	}

	@Override
	@JsonIgnore
	public String getPassword() {
		return null;
	}

	@Override
	public String getUsername() {
		return username;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}

